<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="类型" prop="type">-->
<!--        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">-->
<!--          <el-option label="安全生产制度文本" value="1" />-->
<!--          <el-option label="组织结构图" value="2" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="所属场站" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入所属场站"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="this.queryParams.stationId == null" label="所属区域" prop="areaCode">
        <el-select v-model="queryParams.areaCode"  placeholder="请选择">
          <el-option
            v-for="item in jurisdictionUnitData"
            :key="item.areaCode"
            :label="item.areaName"
            :value="item.areaCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:weightManagement:add']"
        >新增</el-button>
      </el-col>
    </el-row>-->

    <el-table v-loading="loading" :data="weightManagementList" :max-height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column  width="55" align="center" />
      <el-table-column label="所属场站" align="left" prop="stationName"/>
      <el-table-column label="名称" align="left" prop="title"  />
      <el-table-column label="简介" align="left" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:weightManagement:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:weightManagement:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文本或组织结构图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="title" style="width: 57%">
          <el-input v-model="form.title" placeholder="请输入名称" maxlength="30"  show-word-limit/>
        </el-form-item>
        <el-form-item label="简介" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="附件上传" prop="enclosurePath">
          <a v-if="isView == true || form.enclosurePath" class="document-link" target="_blank" :href="form.enclosurePath" title="查看附件">查看附件</a>
          <el-upload v-if="isView == false" ref="enclosurePath"
                     :limit="1"
                     :headers="upload.headers"
                     :action="upload.url"
                     :disabled="upload.isUploading"
                     :before-upload="noticeEnclosureBeforeUpload"
                     :on-progress="handleFileUploadProgress"
                     :on-error="uploadError"
                     :on-success="uploadSuccess"
                     :file-list="upload.enclosurePathList">
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Editor v-model="form.content" />
        </el-form-item>
        <br><br><br>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listWeightManagement, getWeightManagement, delWeightManagement, addWeightManagement, updateWeightManagement, exportWeightManagement } from "@/api/weight/weightManagement";
import { getAreaListByUserId } from "@/api/weight/station";
import Editor from '@/components/Editor';
import { getToken } from "@/utils/auth";
export default {
  name: "WeightManagement",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 管理制度文本与组织结构图表格数据
      weightManagementList: [],
      enclosurePathList: [],
      // 管辖单位
      jurisdictionUnitData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isView: false,
      tableHeight: window.innerHeight - 275,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationId: undefined,
        title: undefined,
        type: undefined,
        stationName: undefined,
        areaCode: undefined,
      },
      // 表单参数
      form: {},
      openView: false,
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    const stationId = this.$route.params && this.$route.params.stationId;
    this.queryParams.stationId=stationId;
    const stationName = this.$route.params && this.$route.params.stationName;
    this.queryParams.stationName=stationName;
    this.getList();
    getAreaListByUserId().then(response =>{
      this.jurisdictionUnitData=response.data;
    });
  },
  methods: {
    /** 查询管理制度文本与组织结构图列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = '1';
      listWeightManagement(this.queryParams).then(response => {
        this.weightManagementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        stationId: undefined,
        title: undefined,
        type: '1',
        content: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        stationName: undefined,
        photoPath: '',
        enclosurePath: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    //详细信息
    handleView(row) {
      this.reset();
      const id = row.id;
      const type = row.type;
      this.$router.push({
        path: "/weightManagement/weightManagementDetail",
        query: {
          id
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.enclosurePath ='';
      this.open = true;
      this.title = "添加管理制度";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWeightManagement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改管理制度";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateWeightManagement(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addWeightManagement(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该条管理制度的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWeightManagement(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有管理制度的图数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportWeightManagement(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    noticeEnclosureBeforeUpload(file) {
      let name = file.name
      let type = name.substring(name.lastIndexOf('.')+1)
      let arry = ["docx","doc","pdf","jpg","png","jpeg","bmp"]
      if (arry.indexOf(type) === -1) {
        this.$message.error('附件格式仅支持docx,doc,pdf,jpg,png,jpeg,bmp格式');
        return false
      }
      let isRightSize = file.size / 1024 / 1024 < 20
      if (!isRightSize) {
        this.$message.error('文件大小超过 20MB')
        return false
      }
      return isRightSize
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    uploadSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.enclosurePath=response.fileName;
    },
    uploadError(response, file, fileList) {
      this.msgError(response.msg);
    },
    // 上传组织结构图
    handleSuccess(response, file) {
      // this.form.content=response.fileName;
      this.form.content=response.url;
    }
  }
};
</script>
<style>
  textarea{
    height: 120px;
  }
</style>
